package com.wlz.pipeline.server;

import com.wlz.pipeline.server.in.NettyInAServerHandler;
import com.wlz.pipeline.server.in.NettyInBServerHandler;
import com.wlz.pipeline.server.in.NettyInCServerHandler;
import com.wlz.pipeline.server.outB.NettyOutDBoundHandler;
import com.wlz.pipeline.server.outB.NettyOutEBoundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 源码学院-ant
 * 只为培养BAT程序员而生
 * http://bat.ke.qq.com
 * 往期视频加群:516212256 暗号:6
 */
public class NettyServer {
    public void bind(int port)throws Exception{

        //指定一个线程组负责accept事件
        EventLoopGroup  bossGroup=new NioEventLoopGroup();
        //指定一个线程组负责读写事件的处理
        EventLoopGroup workGroup=new NioEventLoopGroup();
        try {
            ServerBootstrap b=new ServerBootstrap();//服务端引导程序
            b.group(bossGroup ,workGroup)
                    .channel(NioServerSocketChannel.class)//指定通讯模式为nio模式
                    .childOption(ChannelOption.TCP_NODELAY,true)
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            socketChannel.pipeline().addLast("out D ",new NettyOutDBoundHandler());
                            socketChannel.pipeline().addLast("out E ",new NettyOutEBoundHandler());

                            socketChannel.pipeline().addLast("in A",new NettyInAServerHandler());
                            socketChannel.pipeline().addLast("in B",new NettyInBServerHandler());
                            socketChannel.pipeline().addLast("in C",new NettyInCServerHandler());

                            System.out.println("initchannel end");
                        }
                    });
            ChannelFuture f=b.bind(port).sync();
            System.out.println("server start");
            f.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            //关闭线程资源
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception{
        int port=8080;
        new NettyServer().bind(port);
    }
}
